package net.viral.struts2;

import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.*;
import org.apache.solr.common.params.ModifiableSolrParams;

import java.net.MalformedURLException;
import java.util.ArrayList;

import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.FacetField;
import java.io.IOException;
import java.util.List;
import org.carrot2.clustering.lingo.LingoClusteringAlgorithm;
import org.carrot2.core.Cluster;
import org.carrot2.core.Document;
import java.util.LinkedHashMap;
import java.util.Map;

public class SolrJUtils {
	//public static final String[] CATEGORIES = { "a", "b", "c", "d" };
	public String name;
	private String title;
	private String description;
	private String author;
	private String link;
	private String search;
	private String searchfrom;
	private String pubDate;
	private String category;
	private ArrayList<SolrJUtils> news = new ArrayList<SolrJUtils>();
	Map clusters = new LinkedHashMap<String, Integer>();
	Map facetsMap = new LinkedHashMap<String,String>();
	LingoClusteringAlgorithm stc = new LingoClusteringAlgorithm();



	public String getCategory() {
		//if(category == null)
		//return "*";
		return category;
	}
	
	

	public Map getFacetsMap() {
		return facetsMap;
	}



	public void setCategory(String category) {
		this.category = category;
	}

	public Map getClusters() {
		return clusters;
	}

	public String getSearchfrom() {
		return searchfrom;
	}
	public void setSearchfrom(String searchfrom) {
		this.searchfrom = searchfrom;

	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getTitle() {
		return title;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getDescription() {
		return description;
	}
	public void setLink(String link) {
		this.link = link;
	}
	public String getLink() {
		return link;
	}
	public void setAuthor(String author) {
		if(author.equals(""))
			this.author=null;
		else
			this.author = author;
	}
	public String getAuthor() {
		return author;
	}
	public ArrayList<SolrJUtils> getNews() {
		return news;
	}
	public void setNews(ArrayList<SolrJUtils> news) {
		this.news = news;
	}
	public void setSearch(String search) {
		this.search = search;
	}
	public String getSearch() {
		return search;
	}

	public static void doImport(boolean fullimport){
		SolrServer solr = null;
		QueryResponse response = null;

		try {
			solr = new CommonsHttpSolrServer("http://localhost:8983/solr");
		} catch (MalformedURLException e) {
			System.out.println(e.getMessage());
		}


		//http://localhost:8983/solr/dataimport?command=full-import
		ModifiableSolrParams params = new ModifiableSolrParams();
		params.set("qt", "/dataimport");
		if(fullimport)
			params.set("command", "full-import");
		else
			params.set("command", "delta-import");

		try {
			response = solr.query(params);
		} catch (SolrServerException e) {
			System.out.println(e.getMessage());
		}
	}
	@SuppressWarnings("unchecked")
	public String execute() throws MalformedURLException, SolrServerException,IOException {

		System.out.println("Querying");
		//Get Solr instance
		SolrServer server = new CommonsHttpSolrServer("http://localhost:8983/solr");
		//Random rand = new Random();
		//Construct a SolrQuery 
		SolrQuery query = new SolrQuery();
		QueryResponse rsp;
		String facetLabel;
		
		//get all facets
		query.setQuery( "*:*");
		query.setFacet(true);
		query.addFacetField("category");
		query.setFacetMinCount(2);
		rsp = server.query( query );
		List<FacetField> facets = rsp.getFacetFields();
		for (FacetField facet : facets) {
			//System.out.println(facet);
			for (int i = 0; i < facet.getValueCount(); i++) {
				facetLabel = facet.getValues().get(i)+"";
				if(category!=null&&!category.equals("")&&/*facetLabel.contains(category)&&*/facetLabel.startsWith(category, 0)){
					facetsMap.put("<b>"+facetLabel+"</b>", facetLabel.substring(0, facetLabel.indexOf('(')));
				}
				else{
					facetsMap.put(facetLabel+"", facetLabel.substring(0, facetLabel.indexOf('(')));
				}
			}
		}


		query = new SolrQuery();


		if(search == null){
			search = "*";
			searchfrom = "*";
		}
		else{
			search=search.trim();
			if(search.isEmpty()){
				search = "*";
			}
			else
			{
				search.trim();
				System.out.println("search word is : "+search);
			}
		}
		//query.setQuery( searchfrom +":"+ search);
		query.setQuery("description:"+search+" OR "+"title:"+search);

		query.setRows(100);

		query.setSortField("time", ORDER.desc);
		/*query.setFacet(true);
		query.addFacetField("category");
		query.setFacetMinCount(2);*/

		/*if(searchfrom.equals("category"))
			this.category = search;*/
		if(category!=null&&!category.equals("")){
			query.setFilterQueries("category:\""+getCategory()+"\"");
		}
		System.out.println("Category : "+category);

		rsp = server.query( query );
		//System.out.println(rsp);
		SolrDocumentList docs = rsp.getResults();
		stc.documents = new ArrayList<Document>();


		//SolrDocument d1 = docs.get(1);
		for (SolrDocument d1 : docs) {
			SolrJUtils sj=new SolrJUtils();
			sj.setAuthor((d1.getFieldValue("author")+""));
			sj.setDescription(d1.getFieldValue("description")+"");
			sj.setTitle((d1.getFieldValue("title")+"").replace('[', ' ').replace(']', ' '));
			sj.setLink((d1.getFieldValue("links")+"").replace('[', ' ').replace(']', ' '));
			sj.setPubDate(d1.getFieldValue("time")+"");
			//sj.setDate(d1.getFieldValue("date")+"");
			//System.out.println();
			stc.documents.add(new Document(sj.getTitle(),sj.getDescription(),sj.getLink()));
			news.add(sj);
			//System.out.println("ID : "+d1.getFieldValue("id")+"\nTitle : "+d1.getFieldValue("title")+"\nAuthor : "+d1.getFieldValue("author")+"\nDescription : "+d1.getFieldValue("description"));
			//System.out.println("date is :"+pubDate);
		}


		if(stc.documents == null)
			return "success";


		stc.process();

		if(stc.clusters == null || stc.clusters.size() == 0){
			return "success";
		}

		System.out.println(stc.clusters.size());

		for (Cluster cluster : stc.clusters) {
			if(cluster.getDocuments().size() > 1)
				clusters.put(cluster.getLabel(),cluster.getDocuments().size());
			//System.out.println(cluster.getLabel());
		}
		clusters.remove("Other Topics");

		return "success";


	}
	public void setPubDate(String pubDate) {
		this.pubDate = pubDate;
	}
	public String getPubDate() {
		return pubDate;
	}
}